package hotel.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import hotel.entity.ItemDescription;
import hotel.entity.Payment;
import hotel.entity.Sales;
import hotel.entity.SalesLineItem;
import hotel.service.ISalesService;

@Component
public class SalesServiceImpl<T> extends ServiceImpl<T> implements ISalesService<T> {

	@Override
	public boolean save(Sales sales,List<SalesLineItem> items,Payment payment) {
		try {
			Date date=new Date();
			SimpleDateFormat format=new SimpleDateFormat("yyMMddHHmmss");
			sales.setOrderNumber(format.format(date));
			sales.setSalesTime(date);
			sales=(Sales)dao.saveAndReturn(sales);
			
			//保存Payment
			payment.setSales(sales);
			dao.save(payment);
			
			//保存SalesLineItem
			for(SalesLineItem item:items) {
				item.setSales(sales);
				item.setCheckin_time(date);
				item.setState("已入住");
				//更新房间状态
				dao.executeUpdate("update Room r set r.state ='已入住' where r.roomid = "+item.getRoom().getRoomid());
				item=(SalesLineItem)dao.saveAndReturn(item);
				//保存ItemDescription
				for(ItemDescription desc:item.getDescriptions()) {
					desc.setSalesLineItem(item);
					dao.save(desc);
				}
			}
			
			return true;
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}

	@Override
	public double getTotalSale() {
		String totalSale=dao.uniqueResult("select sum(totalPrice) from Sales");
		if(totalSale!=null)
			return Double.parseDouble(totalSale);
		return 0;
	}

	@Override
	public int getSalesCount() {
		return dao.getTotalCount("Sales");
	}

	@Override
	public List<T> paging(int firstResult, int maxResult) {
		return dao.paging("Sales", firstResult, maxResult);
	}

	@Override
	public Map<String, Double> getSaleStatistic() {
		HashMap<String,Double> map=new LinkedHashMap<String,Double>();
		for(Object[] obj:dao.sqlQuery("SELECT DATE_FORMAT( salesTime, \"%Y-%m-%d\" ) as time, SUM(totalPrice) as price FROM sales WHERE salesid > (SELECT MAX(salesid) FROM sales) - 10 GROUP BY time ORDER BY salesTime ASC LIMIT 10")) {
			map.put((String)obj[0], (Double)obj[1]);
		}
		return map;
	}
}
